package com.engine.workflow.zhlx.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.jobs.common.DocUtil;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2023-05-10
 * @Description: 调用自定义流程接口
 * @ModifyLog:
 **/

public class WeaWorkflowWeb extends BaseBean {
    /**
     * @Description: 流程创建
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023/7/17
     */

    @POST
    @Path("/doCreateRequest")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String doCreateRequest(JSONObject paramsJson) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        WfUtil wfUtil = new WfUtil();
        int seccategory = 59567;
        try {
            writeLog(">>>>>doCreateRequest>>>paramsJson=" + paramsJson);
            String workflowId = Util.null2String(paramsJson.getString("workflowId"));
            String requestName = Util.null2String(paramsJson.getString("requestName"));
            String mainData = Util.null2String(paramsJson.getString("mainData"));
            String detailData = Util.null2String(paramsJson.getString("detailData"));
            String isnextFlow = Util.null2String(paramsJson.getString("isnextFlow"));
            String workcode = Util.null2String(paramsJson.getString("workcode"));
            Map<String, Object> returnParamsMap = wfUtil.checkReqParams(workflowId, requestName, mainData, isnextFlow, workcode);
            String paramsCode = Util.null2String(returnParamsMap.get("code"));
            writeLog(">>>>>doCreateRequest>>>paramsCode=" + paramsCode);
            if (!"SUCCESS".equals(paramsCode)) {
                apidatas = returnParamsMap;
            } else {
                String userId = wfUtil.getResourceid(workcode);
                User user = new User(Util.getIntValue(userId));
                boolean isMainArr = wfUtil.isJSONArray(mainData);
                if (!isMainArr) {
                    apidatas.put("code", "PARAM_ERROR");
                    apidatas.put("data", "");
                    apidatas.put("message", "mainData参数不是JSON数组格式");
                } else {
                    JSONArray mainDatalist = JSONArray.parseArray(mainData);
                    Map<String, Object> mainMap = new HashMap<String, Object>();
                    for (int i = 0; i < mainDatalist.size(); i++) {
                        JSONObject mainFields = mainDatalist.getJSONObject(i);
                        String fieldName = Util.null2String(mainFields.getString("fieldName"));
                        String fieldValue = Util.null2String(mainFields.getString("fieldValue"));
                        if (wfUtil.isJSONArray(fieldValue)) {
                            String docids = "";
                            JSONArray fileList = JSONArray.parseArray(fieldValue);
                            for (int l = 0; l < fileList.size(); l++) {
                                JSONObject fileJson = fileList.getJSONObject(l);
                                String filePath = Util.null2String(fileJson.getString("filePath"));
                                String fileName = Util.null2String(fileJson.getString("fileName"));
                                Map<String, Object> retMap = DocUtil.downloadByUrl(filePath);
                                if (Util.null2String(retMap.get("code")).equals("0")) {
                                    String filepath = Util.null2String(retMap.get("data"));
                                    writeLog(">>>>>doCreateRequest>>>filepath=" + filepath);
                                    int imagefileid = DocUtil.saveImageFile(fileName, filepath);
                                    writeLog(">>>>>doCreateRequest>>>imagefileid=" + imagefileid);
                                    int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                                    writeLog(">>>>>doCreateRequest>>>docid=" + docid);
                                    docids += "".equals(docids) ? docid : "," + docid;
                                }
                            }
                            fieldValue = docids;
                        }
                        mainMap.put(fieldName, fieldValue);
                    }
                    String newRequestid = wfUtil.WorkflowCreateByRequestMap(userId, workflowId, requestName, isnextFlow, mainMap);
                    writeLog(">>>>>doCreateRequest>>>newRequestid=" + newRequestid);
                    if (Util.getIntValue(newRequestid) > 0) {
                        if (!"".equals(detailData)) {
                            boolean isDtlArr = wfUtil.isJSONArray(mainData);
                            if (!isDtlArr) {
                                apidatas.put("code", "PARAM_ERROR");
                                apidatas.put("data", "");
                                apidatas.put("message", "detailData参数不是JSON数组格式");
                            } else {
                                JSONArray detailDatalist = JSONArray.parseArray(detailData);
                                String mainid = Util.null2String(wfUtil.getIdByRequestId(workflowId, newRequestid));
                                int dtlTableSumCount = detailDatalist.size();
                                int dtlTableSuccCount = 0;
                                for (int i = 0; i < detailDatalist.size(); i++) {
                                    JSONObject detailDatas = detailDatalist.getJSONObject(i);
                                    String dtltableName = Util.null2String(detailDatas.getString("tableDBName"));
                                    if (!"".equals(dtltableName)) {
                                        writeLog(">>>>>doUpdateRequest>>>detailData>>>>dtltableName=" + dtltableName);
                                        String tableRecords = Util.null2String(detailDatas.getString("workflowRequestTableRecords"));
                                        boolean istableArr = wfUtil.isJSONArray(tableRecords);
                                        if (!"".equals(tableRecords) && istableArr) {
                                            JSONArray recordslist = JSONArray.parseArray(tableRecords);
                                            int sumCount = recordslist.size();
                                            int succCount = 0;
                                            for (int j = 0; j < recordslist.size(); j++) {
                                                Map<String, Object> detailMap = new HashMap<String, Object>();
                                                JSONObject records = recordslist.getJSONObject(j);
                                                String recordOrder = Util.null2String(records.getString("recordOrder"));
                                                writeLog("detailData>>>>recordOrder=" + recordOrder);
                                                String tableFields = Util.null2String(records.getString("workflowRequestTableFields"));
                                                if (!"".equals(tableFields) && wfUtil.isJSONArray(tableFields)) {
                                                    JSONArray tableFieldslist = JSONArray.parseArray(tableFields);
                                                    for (int k = 0; k < tableFieldslist.size(); k++) {
                                                        JSONObject detailFields = tableFieldslist.getJSONObject(k);
                                                        String fieldName = Util.null2String(detailFields.getString("fieldName"));
                                                        String fieldValue = Util.null2String(detailFields.getString("fieldValue"));
                                                        if (wfUtil.isJSONArray(fieldValue)) {
                                                            String docids = "";
                                                            JSONArray fileList = JSONArray.parseArray(fieldValue);
                                                            for (int l = 0; l < fileList.size(); l++) {
                                                                JSONObject fileJson = fileList.getJSONObject(l);
                                                                String filePath = Util.null2String(fileJson.getString("filePath"));
                                                                String fileName = Util.null2String(fileJson.getString("fileName"));
                                                                Map<String, Object> retMap = DocUtil.downloadByUrl(filePath);
                                                                if (Util.null2String(retMap.get("code")).equals("0")) {
                                                                    String filepath = Util.null2String(retMap.get("data"));
                                                                    int imagefileid = DocUtil.saveImageFile(fileName, filepath);
                                                                    int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                                                                    docids += (docids.equals("") ? docid : ("," + docid));
                                                                }
                                                            }
                                                            fieldValue = docids;
                                                        }
                                                        detailMap.put(fieldName, fieldValue);
                                                    }
                                                    detailMap.put("mainid", mainid);
                                                    boolean isDtlUpdate = wfUtil.updateDetailData(dtltableName, detailMap);
                                                    writeLog(">>>>>doUpdateRequest>>>isDtlUpdate=" + isDtlUpdate);
                                                    if (isDtlUpdate) {
                                                        succCount++;
                                                    }
                                                }
                                            }
                                            if (succCount == sumCount) {
                                                dtlTableSuccCount++;
                                            }
                                            writeLog(">>>>>doUpdateRequest>>>succCount=" + succCount + ",sumCount=" + sumCount);
                                        }
                                    }
                                }
                                writeLog(">>>>>doUpdateRequest>>>dtlTableSuccCount=" + dtlTableSuccCount + ",dtlTableSumCount=" + dtlTableSumCount);
                                if (dtlTableSumCount == dtlTableSuccCount) {
                                    apidatas.put("code", "SUCCESS");
                                    JSONObject datajson = new JSONObject();
                                    datajson.put("requestid", newRequestid);
                                    apidatas.put("data", datajson);
                                    apidatas.put("message", "流程创建成功");
                                } else {
                                    wfUtil.deleteWorkflow(Util.getIntValue(newRequestid), Util.getIntValue(userId));
                                    apidatas.put("code", "PARAM_ERROR");
                                    apidatas.put("data", "");
                                    apidatas.put("message", "detailData参数错误，明细表更新失败");
                                }
                            }
                        } else {
                            apidatas.put("code", "SUCCESS");
                            JSONObject datajson = new JSONObject();
                            datajson.put("requestid", newRequestid);
                            apidatas.put("data", datajson);
                            apidatas.put("message", "流程创建成功");
                        }
                    } else {
                        apidatas.put("code", "PARAM_ERROR");
                        JSONObject dataJson = new JSONObject();
                        dataJson.put("requestid", newRequestid);
                        apidatas.put("data", dataJson);
                        apidatas.put("message", "流程创建失败");
                    }
                }

                writeLog(">>>>>doCreateRequest>>>apidatas=" + apidatas.toString());
            }

        } catch (Exception e) {
            System.out.println("程序内部异常:" + e);
            apidatas.put("code", "PARAM_ERROR");
            apidatas.put("data", "");
            apidatas.put("message", "请求JSON数据格式异常");
        }
        writeLog(">>>>>doCreateRequest>>>apidatas=" + apidatas.toString());
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * @Description: 流程控制节点流向
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023/7/17
     */
    @POST
    @Path("/doForwardRequest")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String doForwardRequest(JSONObject paramsJson) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        WfUtil wfUtil = new WfUtil();
        try {
            String requestId = Util.null2String(paramsJson.getString("requestId"));
            String workflowId = Util.null2String(paramsJson.getString("workflowId"));
            String isLeave = Util.null2String(paramsJson.getString("isLeave"));
            String workcode = Util.null2String(paramsJson.getString("workcode"));
            writeLog(">>>>>doForwardRequest>>>paramsJson=" + paramsJson);
            Map<String, Object> returnParamsMap = wfUtil.checkReqParams1(requestId, workflowId, isLeave);
            String paramsCode = Util.null2String(returnParamsMap.get("code"));
            writeLog(">>>>>doForwardRequest>>>paramsCode=" + paramsCode);
            if (!"SUCCESS".equals(paramsCode)) {
                apidatas = returnParamsMap;
            } else {
                RecordSet rs = new RecordSet();
                String tableName = "formtable_main_" + wfUtil.getFormid(workflowId);
                boolean flag = rs.executeUpdate("update " + tableName + " set sfly=? where requestid=?", isLeave, requestId);
                if (flag) {
                    String userId = wfUtil.getResourceid(workcode);
                    String resultStr = wfUtil.submitWorkflow(Util.getIntValue(requestId), Util.getIntValue(userId));
                    writeLog(">>>>>doForwardRequest>>>resultStr=" + resultStr);
                    if ("success".equals(resultStr)) {
                        apidatas.put("code", "SUCCESS");
                        JSONObject dataJson = new JSONObject();
                        dataJson.put("status", resultStr);
                        apidatas.put("data", dataJson);
                        apidatas.put("message", "流程提交成功");
                    } else {
                        apidatas.put("code", "NO_PERMISSION");
                        JSONObject dataJson = new JSONObject();
                        dataJson.put("status", resultStr);
                        apidatas.put("data", dataJson);
                        apidatas.put("message", "流程提交失败");
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("code", "SYSTEM_INNER_ERROR");
            apidatas.put("data", "");
            apidatas.put("message", "请求JSON数据格式异常");
        }
        writeLog(">>>>>doForwardRequest>>>apidatas=" + apidatas.toString());
        return JSONObject.toJSONString(apidatas);
    }

}
